// components/location/index.js
var QQMapWX = require('./../../sdk/qqmap-wx-jssdk.min.js');
var qqmapsdk;
const app = getApp();
Component({
  /**
   * 组件的属性列表
   */
  properties: {

  },

  /**
   * 组件的初始数据
   */
  data: {
    address: "地址加载中..."
  },
  lifetimes: {
    attached: function () {
      // 在组件实例进入页面节点树时执行
    },
    detached: function () {
      // 在组件实例被从页面节点树移除时执行
    }
  },
  pageLifetimes: {
    // 组件所在页面的生命周期函数
    show: function () {
      this.init();
    },
    hide: function () {},
    resize: function () {},
  },
  /**
   * 组件的方法列表
   */
  methods: {
    init() {
      var self = this;
      console.info("获取地址");

      
      wx.getStorage({
        key: "location",
        success(result) {
        
          var res = result.data;
          if (res.address) {
            console.log(res.address);
            self.setData({
              address: res.address
            });
            app.address = res.address;
            app.lat = res.lat;
            app.lng = res.lng;
          } else {
            self.initLocationAddress();
          }

        },
        fail() {
          self.initLocationAddress();
        }
      })


    },
    initLocationAddress() {
      var self = this;
      qqmapsdk = new QQMapWX({
        key: 'LUCBZ-NE5KK-7UEJH-AFXWU-3Q6SO-PPFQI'
      });
      wx.getLocation({
        type: 'gcj02',
        success(res) {
          console.log(res);
          qqmapsdk.reverseGeocoder({
            location: res,
            success: function (data) {
              console.log(data);
              if (data.result.address) {
                self.setData({
                  address: data.result.address
                });
                var loc={};
                loc.address = data.result.address;
                loc.lat = res.latitude;
                loc.lng = res.longitude;

                app.address = loc.address;
                app.lat = loc.lat;
                app.lng = loc.lng;

                app.setStorage("location",loc);

              }
            },
            fail: function (error) {
              console.error(error);
            },
            complete: function (res) {
              //console.log(res);
            }
          });

          const latitude = res.latitude
          const longitude = res.longitude
          const speed = res.speed
          const accuracy = res.accuracy
          app.lat = latitude;
          app.lng = longitude;
        }
      })

    }
    

  }
})